package com.sunday.shoufen.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.BaseLazyFragment;
import com.sunday.shoufen.entity.FanEntity;
import com.sunday.shoufen.entity.Fans;
import com.sunday.shoufen.http.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/11/1.
 */

public class CouponMoneyFragment extends BaseLazyFragment {
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;


    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<Fans> dataSet = new ArrayList<>();
    private CommonAdapter<Fans> adapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private int sort;


    public static FansListFragment newInstance(int sort) {
        FansListFragment fragment = new FansListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("sort", sort);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            sort = getArguments().getInt("sort");
        }
    }

    public int getSort() {
        return sort;
    }

    public void setSort(int sort) {
        this.sort = sort;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_list_shop, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;
        memberId = BaseApp.getInstance().getMember().getId();
        getData();
    }


    private void initRefreshLayout() {
        adapter = new CommonAdapter<Fans>(mContext, R.layout.list_fans_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, Fans fans) {
                bind(holder, fans);
            }
        };
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void bind(ViewHolder holder, Fans fans) {
        CircleImageView userLogo = holder.getView(R.id.fans_logo);
        TextView userName = holder.getView(R.id.fans_name);
        TextView userTime = holder.getView(R.id.fans_time);
        Glide.with(mContext)
                .load(fans.getLogo())
                .into(userLogo);
        userName.setText(fans.getNickName());
        userTime.setText(fans.getTime());

    }

    private void getData() {
        Call<ResultDO<FanEntity>> call = ApiClient.getApiAdapter().getMyMember(1, memberId, sort, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<FanEntity>>() {
            @Override
            public void onResponse(Call<ResultDO<FanEntity>> call, Response<ResultDO<FanEntity>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult().getMembers());
                    if (response.body().getResult().getMembers().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<FanEntity>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
}
